package com.rpa.server.servicerpaserver.crawler.operate;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.rpa.secure.servicerpasecure.common.constant.JumpJudgmentConstant;
import com.rpa.secure.servicerpasecure.common.constant.MessageConstant;
import com.rpa.secure.servicerpasecure.common.constant.UrlConstant;
import com.rpa.secure.servicerpasecure.common.exception.TaskException;
import com.rpa.server.servicerpaserver.crawler.entity.Score;
import com.rpa.server.servicerpaserver.crawler.entity.Stu;
import com.rpa.server.servicerpaserver.crawler.entity.User;
import com.rpa.server.servicerpaserver.crawler.entity.dto.ScoreDto;
import com.rpa.server.servicerpaserver.crawler.mapper.ScoreMapper;
import com.rpa.server.servicerpaserver.crawler.service.StuService;
import com.rpa.server.servicerpaserver.crawler.service.UserService;
import com.rpa.server.servicerpaserver.util.CookieSerialize;
import io.github.bonigarcia.wdm.WebDriverManager;
import lombok.extern.slf4j.Slf4j;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.*;
import java.util.concurrent.CompletableFuture;

/**
 * @className: ScoreOperate
 * @author: lzt
 * @date: 2025/2/18 9:27
 * @Version: 1.0
 * @description:
 */
@Component
@Slf4j
@DependsOn("uerServiceImpl")
public class ScoreOperate {
    @Autowired
    private ScoreMapper scoreMapper;
    @Autowired
    private final UserService userService;
    @Autowired
    private StuService stuService;

    @Autowired
    public ScoreOperate(UserService uerService) {
        this.userService = uerService;
    }

    public void submitScore(ScoreDto scoreDto) {
        log.info("scoreDto:{}", scoreDto);
        LambdaQueryWrapper<Score> eq = new LambdaQueryWrapper<Score>()
                .eq(Score::getAccountId, scoreDto.getAccountId())
                .eq(Score::getCourseId, scoreDto.getCourseId())
                .eq(Score::getClazzId, scoreDto.getClazzId());
        List<Map<String, Object>> scoreTotal = scoreMapper.getScoreTotal(eq);
        if (CollUtil.isNotEmpty(scoreTotal)) {
            User user = userService.getById(scoreDto.getAccountId());
            if (user == null) {
                throw new TaskException(MessageConstant.NO_USER);
            }
            WebDriverManager.chromedriver().setup();
            ChromeOptions options = new ChromeOptions();
            options.addArguments("--disable-gpu");
            options.addArguments("--remote-allow-origins=*");
            options.addArguments("--start-maximized");
            WebDriver chromeDriver = new ChromeDriver(options);

            String stuAccount = user.getStuAccount();
            String stuPassword = user.getStuPassword();

            String id = user.getId().toString();
            try {

                chromeDriver.get(UrlConstant.PASSPORT_EDUCATIONAL);
                WebDriverWait wait = new WebDriverWait(chromeDriver, Duration.ofSeconds(60));

                wait.until(d -> d.getCurrentUrl().startsWith("https://jwgl.baiyunu.edu.cn/"));
                System.out.println("登录页面加载完成");
                String currentUrl = chromeDriver.getCurrentUrl();
                System.out.println("当前URL：" + currentUrl);
                WebElement iframe = chromeDriver.findElement(By.id("frm_login"));
                chromeDriver.switchTo().frame(iframe);

                // 选择用户类型
                WebElement selectElement = chromeDriver.findElement(By.xpath("//select[@name='Sel_Type']"));
                Select userTypeSelect = new Select(selectElement);
                userTypeSelect.selectByValue("TEA");

                // 输入账号
                WebElement accountElement = chromeDriver.findElement(By.id("txt_asmcdefsddsd"));
                accountElement.clear();
                accountElement.sendKeys(stuAccount);

                // 输入密码
                JavascriptExecutor js = (JavascriptExecutor) chromeDriver;
                js.executeScript("document.getElementById('txt_pewerwedsdfsdff').style.display='block';");
                WebElement password = wait.until(ExpectedConditions.elementToBeClickable(By.id("txt_pewerwedsdfsdff")));
                password.clear();
                password.sendKeys(stuPassword);
                WebElement logBut = chromeDriver.findElement(By.xpath("//*[@id=\"btn_login\"]"));
                logBut.click();
                if (wait.until(ExpectedConditions.titleIs(JumpJudgmentConstant.REGISTER_INDEX_STU))) {
                    LambdaQueryWrapper<Stu> eq1 = new LambdaQueryWrapper<Stu>()
                            .eq(Stu::getId, scoreDto.getStuValueId());
                    Stu stu = stuService.getOne(eq1);
                    chromeDriver.get(UrlConstant.PASSPORT_EDUCATIONAL + stu.getUrlLink());
                    try {
                        wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("body")));
                        WebElement iframe1 = wait.until(ExpectedConditions.presenceOfElementLocated(By.name("frmRpt")));
                        chromeDriver.switchTo().frame(iframe1);
                        WebElement scoreTable = chromeDriver.findElement(By.xpath("//*[@id=\"form1\"]/table[2]"));
                        List<WebElement> rows = scoreTable.findElements(By.tagName("tr"));
                        for (Map<String, Object> score : scoreTotal) {
                            String userName = (String) score.get("userName");
                            String studentNumber = (String) score.get("studentNumber");
                            // 创建一个列表来存储分数，按顺序存储
                            List<String> scores = new ArrayList<>();
                            scores.add(MapUtil.getStr(score,"originallyScore1"));
                            scores.add(MapUtil.getStr(score,"originallyScore2"));
                            scores.add(MapUtil.getStr(score,"originallyScore3"));
                            scores.add(MapUtil.getStr(score,"originallyScore4"));
                            // 过滤掉空值
                            scores.removeIf(StrUtil::isEmpty);

                            String totalScore = MapUtil.getStr(score,"totalScore");
                            for (WebElement row : rows) {
                                List<WebElement> cells = row.findElements(By.tagName("td"));
                                if (cells.size() >= 2) {
                                    String rowStudentNumber = cells.get(1).getText().trim();
                                    String rowUserName = cells.get(2).getText().trim();
                                    if ("学号".equals(rowStudentNumber) || "姓名".equals(rowUserName) || "技能".equals(rowUserName) || "技能".equals(rowStudentNumber)) {
                                        continue;
                                    }
                                    if (rowUserName.equals(userName) && rowStudentNumber.equals(studentNumber)) {
                                        int scoreIndex = 0; // 用于跟踪分数列表的索引
                                        for (int i = 5; i < cells.size() && scoreIndex < scores.size(); i++) {
                                            WebElement scoreInput = cells.get(i).findElement(By.tagName("input"));
                                            if (scoreInput != null) {
                                                // 使用 JavaScript 设置 input 元素的 value 属性
                                                ((JavascriptExecutor) chromeDriver).executeScript("arguments[0].setAttribute('value', arguments[1]);", scoreInput, scores.get(scoreIndex).toString());
                                                scoreIndex++;
                                            }
                                        }
                                        if (totalScore != null) {
                                            WebElement totalScoreInput = cells.get(cells.size()-3).findElement(By.tagName("input"));
                                            if (totalScoreInput != null) {
                                                // 使用 JavaScript 设置 input 元素的 value 属性
                                                ((JavascriptExecutor) chromeDriver).executeScript("arguments[0].setAttribute('value', arguments[1]);", totalScoreInput, totalScore.toString());
                                            }
                                        }
                                        break;
                                    }
                                }
                            }
                        }
                        // 页面加载完成后的操作
                    } catch (TimeoutException e) {
                        // 处理超时情况
                        System.out.println("页面加载超时");
                    }
                } else {
                    log.error("登录失败，账号为: {}，存入主键为:{}", stuAccount, id);
                }
            } catch (Exception e) {
                log.error("登录失败，账号为: {}，存入主键为:{},异常信息为:{}", stuAccount, id, e);
            }
        }
    }
}
